package com.study.testSpringBoot.download;

import cn.hutool.core.lang.UUID;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author wc_phz
 * @ClassName DownloadFile
 * @Description: [ ]
 * @date 2020/3/6 10:19
 */
@RestController
public class DownloadFile {


    @RequestMapping("/downloadFile/{path}.{suffix}")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "path")String path,
                             @PathVariable(value = "suffix")String suffix){
        DataOutputStream out = null;
        FileInputStream fis = null;
        File file = null;
        File file1 = null;
        try{
            String filePath = System.getProperty("java.io.tmpdir");
            filePath = filePath + "/"+ UUID.randomUUID().toString().replace("-","");
            file1 = new File(filePath);
            file1.mkdir();
            String contentType = "application/octet-stream";
            String p = null;
            if("png".equals(suffix.toLowerCase()) || "jpg".equals(suffix.toLowerCase()) || "jpeg".equals(suffix.toLowerCase())){
                if("png".equals(suffix.toLowerCase())){

                    contentType = "image/png";
                }else {

                    contentType = "image/jpeg";
                }
                p = request.getParameter("x-image-process");
            }

            file = HuaWeiStorageUtil.downloadFile("laozi-autopublic-east",path+"."+suffix,filePath+"/"+path+"."+suffix,p);

            fis = new FileInputStream(file);
            response.setContentType(contentType);
            response.setHeader("Content-disposition", "attachment; filename="+file.getName());
            response.setHeader("filename", file.getName());
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("ETag", file.hashCode()+"");

            out = new DataOutputStream(response.getOutputStream());

            byte[] bytes = new byte[4096];
            int num = -1;
            while((num = fis.read(bytes)) != -1) {
                out.write(bytes, 0, num);
            }
            out.flush();
            out.close();
            fis.close();
            FileUtils.deleteDirectory(file1);
        }catch(Exception e){
            e.printStackTrace();
            if(e instanceof FileNotFoundException) {
                StringBuffer url = request.getRequestURL();
                String key = url + "visitedCount";
                Integer count = (Integer) request.getSession().getAttribute(key);
                count = (count == null ? 0 : count) + 1;
                request.getSession().setAttribute(key, count);
                System.out.println("出现了多少次下载错误呢 = " + count);
                if(count < 3) {
                    downloadFile(request, response, path, suffix);
                }
            }
        }
        finally{
            if(file1!=null){
                try {
                    FileUtils.deleteDirectory(file1);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
